//package com.gy.controller.export;
//
//import com.gy.entity.Export.ExportRequest;
//import com.gy.result.Result;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.v3.oas.annotations.parameters.RequestBody;
//import lombok.RequiredArgsConstructor;
//import org.apache.commons.io.FileUtils;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.File;
//import java.io.FileNotFoundException;
//import java.io.IOException;
//import java.net.URLEncoder;
//import java.util.Map;
//import java.util.UUID;
//
//@RestController
//@RequestMapping("/export")
//@RequiredArgsConstructor
//@CrossOrigin
//public class ExportController {
//
//    private final RedisTemplate<String, Object> redisTemplate;
//    private final ExportService exportService;
//
//    @PostMapping("/async")
//    @ApiOperation("提交Excel导出任务")
//    public Result<String> submitExport(@RequestBody ExportRequest request) {
//        // 打印请求的 fields 和 data 确认数据是否到达
//        System.out.println("Received fields: " + request.getFields());
//        System.out.println("Received data: " + request.getData());
//
//        if (request.getFields() == null || request.getFields().isEmpty()) {
//            return Result.error("导出字段为空，请选择导出字段");
//        }
//
//        // 继续执行导出逻辑
//        String taskId = UUID.randomUUID().toString();
//        String redisKey = "export:task:" + taskId;
//        redisTemplate.opsForHash().put(redisKey, "status", "processing");
//        exportService.exportAsync(taskId, request);
//
//        return Result.success(taskId);
//    }
//
//
//    @GetMapping("/status/{taskId}")
//    public Result<Map<Object, Object>> getExportStatus(@PathVariable String taskId) {
//        String redisKey = "export:task:" + taskId;
//        Map<Object, Object> status = redisTemplate.opsForHash().entries(redisKey);
//        return Result.success(status);
//    }
//
//    @GetMapping("/download/{taskId}")
//    public void download(@PathVariable String taskId, HttpServletResponse response) throws IOException {
//        String redisKey = "export:task:" + taskId;
//        Object status = redisTemplate.opsForHash().get(redisKey, "status");
//        if (!"success".equals(status)) {
//            throw new IllegalStateException("任务未完成或失败");
//        }
//
//        String filePath = (String) redisTemplate.opsForHash().get(redisKey, "filePath");
//        File file = new File(filePath);
//        if (!file.exists()) {
//            throw new FileNotFoundException("文件未找到");
//        }
//
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("exported_StudentAward.xlsx", "UTF-8"));
//
//        FileUtils.copyFile(file, response.getOutputStream());
//    }
//}
